<?php
session_start();

/**
 * Script used to create a new user in the database
 */

require_once '../core/db.php';
// Return json encoded data 
header ('Content-type: application/json');
define ('SALT', 'ThisIsth3sal7'); // NEVER CHANGE!
define ('SITEKEY', 'ASiteSpecificArbitraryLengthStringThatIsUsedToSeedTheHashingAlgorithm'); //NEVER CHANGE!

//Checks that userName is not allready registered, if so, return true
if(isset($_POST['userNameCheck'])){
	$sql = "SELECT userName FROM siteUsers WHERE userName=:userName";
	$query = $db -> prepare($sql);
	$query -> bindParam(':userName', $_POST['userName']);
	$query -> execute();
	$res = $query -> fetch();
	if(isset($res['userName'])){
		userCheck("true");
	}else{
		userCheck("false");
	}
}

// Checks that email is not allready registered, if so, return true
if(isset($_POST['emailCheck'])){
	$sql = "SELECT email, userID FROM siteUsers WHERE email=:email";
	$query = $db -> prepare($sql);
	$query -> bindParam(':email', $_POST['email']);
	$query -> execute();
	$res = $query -> fetch();
	if(isset($res['email'])){ // If user is the owner of the email
		if($res['userID'] == $_SESSION['user'] && $res['email'] == $_POST['email']){
			userCheck("replicate");
		}else{
			userCheck("true");
		}
	}else {
		userCheck("false");
	}
}
//Inserting the user to the DB
$db -> beginTransaction();
$db -> query('LOCK TABLES siteUsers WRITE');
$query = "INSERT INTO siteUsers (userName, userRealName, email, homeTown) 
		VALUES (:userName, :userRealName, :email, :town)";
$result = $db -> prepare($query);
$result -> bindParam(':userName', $_POST['userName']);
$result -> bindParam(':userRealName', $_POST['userRealName']);
$result -> bindParam(':email', $_POST['email']);
if(isset($_POST['town']) ||  $_POST['town'] != ""){
	$result -> bindParam(':town',  $_POST['town']);	
}else{
	$result -> bindParam(':town', NULL);
}
$result -> execute();
if($result -> rowCount() == 0){
	$db -> rollBack();
	$db -> query("UNLOCK TABLES");
	userCheck('Username or email already exists!');
}
$result -> closeCursor();
$result = $db -> prepare('SELECT LAST_INSERT_ID() AS userID');
$result -> execute();
$result = $result -> fetch();
if($result){
	$uid = $result['userID'];
}else{
	$db -> rollBack();
	$db -> query("UNLOCK TABLES");
	userCheck(' Error getting new userID');
}
$result = NULL;
$query = 'UPDATE siteUsers SET password=:pwd WHERE userID=:userID';
$result = $db -> prepare($query);
$result -> bindParam(':userID', $uid);
$pwd = $uid.$_POST['pwd'].SALT;
$result -> bindParam(':pwd', hash_hmac('sha512', $pwd, SITEKEY));
$result -> execute();
if($result -> rowCount() == 0){
	$db -> rollBack();
	$db -> query("UNLOCK TABLES");
	userCheck('Unable to updatePassword');
}
$db -> commit();
$_SESSION['user'] = $_POST['userName'];
userCheck("OK");
	

function userCheck($msg){
	die (json_encode(array("respond" => $msg)));
}
?>